package com.xtgg.more;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.login.LoginActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.ToastUtil;
import com.xtgg.util.Utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MessageCenterActivity extends BaseActivity implements
		OnClickListener {
	MyAdapter mAdapter;
	ArrayList<JSONObject> mArray = new ArrayList<JSONObject>();
	ArrayList<String> mSelectArray = new ArrayList<String>();

	int mRowNum = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_message_center);

		((TextView) findViewById(R.id.center)).setText("消息中心");
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.del).setOnClickListener(this);
		findViewById(R.id.unread).setOnClickListener(this);

		final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews
				.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.DISABLED);
		ptrlvHeadlineNews
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						sendHttpRequest();
					}
				});

		ListView listview = ptrlvHeadlineNews.getRefreshableView();
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				JSONObject item = mArray.get(arg2 - 1);
				if (findViewById(R.id.bottom).getVisibility() == View.VISIBLE) {
					if (mSelectArray.contains(item.getString("pushid"))) {
						mSelectArray.remove(item.getString("pushid"));
					} else {
						mSelectArray.add(item.getString("pushid"));
					}
					mAdapter.notifyDataSetChanged();
					return;
				}

				item.put("isread", "1");
				mAdapter.notifyDataSetChanged();

				Intent intent = new Intent(MessageCenterActivity.this,
						MessageDetailActivity.class);
				intent.putExtra("info", item.toString());
				startActivity(intent);
			}
		});

		sendHttpRequest();
	}

	class MyAdapter extends BaseAdapter implements OnClickListener {
		public int getCount() {
			return mArray.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_msg, null);
				foodHold.img = (ImageView) convertView.findViewById(R.id.img);
				foodHold.content = (TextView) convertView
						.findViewById(R.id.content);
				foodHold.time = (TextView) convertView.findViewById(R.id.time);
				foodHold.title = (TextView) convertView
						.findViewById(R.id.title);

				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}

			JSONObject item = mArray.get(position);
			foodHold.time.setText(Utils.formatDate(item.getString("pushtime"),
					"yyyy/MM/dd"));
			foodHold.content.setText(item.getString("content"));

			foodHold.img.setVisibility(View.VISIBLE);
			if (findViewById(R.id.bottom).getVisibility() == View.VISIBLE) {
				if (mSelectArray.contains(item.getString("pushid"))) {
					foodHold.img.setImageResource(R.drawable.ic_msg_on);
				} else {
					foodHold.img.setImageResource(R.drawable.ic_msg_off);
				}

				foodHold.img.setOnClickListener(this);
			} else {
				foodHold.img.setImageResource(R.drawable.ic_unread);
				foodHold.img.setOnClickListener(null);
				if (item.getInteger("isread") == 1) {
					foodHold.img.setVisibility(View.INVISIBLE);
				}
			}

			if (item.getInteger("isread") == 0) {
				foodHold.title.setTextColor(Color.parseColor("#404040"));
			} else {
				foodHold.title.setTextColor(Color.parseColor("#808080"));
			}

			foodHold.img.setTag(String.valueOf(position));
			return convertView;
		}

		@Override
		public void onClick(View arg0) {
			int index = Integer.valueOf((String) arg0.getTag());
			JSONObject item = mArray.get(index);

			if (mSelectArray.contains(item.getString("pushid"))) {
				mSelectArray.remove(item.getString("pushid"));
				((ImageView) arg0).setImageResource(R.drawable.ic_msg_off);
			} else {
				mSelectArray.add(item.getString("pushid"));
				((ImageView) arg0).setImageResource(R.drawable.ic_msg_on);
			}
		}
	}

	void delHttpRequest(String info) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					mSelectArray.removeAll(mSelectArray);
					findViewById(R.id.bottom).setVisibility(View.GONE);

					reloadData();
				} 
				else if (ruser.getState().equals("2")) 
				{showExitDialog();} else {
					ToastUtil.showToastWithAlertPic(ruser.getMessage());
				}

				((PullToRefreshListView) findViewById(R.id.listview))
						.onRefreshComplete();
			}
		};

		StringBuffer buffer = new StringBuffer();
		for (String infoid : mSelectArray) {
			if (buffer.length() > 0)
				buffer.append(",");
			buffer.append(infoid);
		}

		RequestParams params = new RequestParams();
		params.put("act", "operateAppLog");
		params.put("type", info);
		params.put("pushid", buffer.toString());

		MgqRestClient.post(Constants.INFOMGT, params, loginHandler);
	}

	public final class FoodHolder {
		public ImageView img;
		public TextView content;
		public TextView time;
		public TextView title;
	}

	public void reloadData() {
		mRowNum = 0;
		mArray.removeAll(mArray);
		sendHttpRequest();
	}

	private void sendHttpRequest() {
		boolean show = true;
		if (mArray.size() > 0)
			show = false;

		MgqDataHandler loginHandler = new MgqDataHandler(this, show, false) {
			@Override
			public void onSuccess(String response) {
				Resp ruser = JSON.parseObject(response, Resp.class);
				if (ruser.getState().equals("1")) {
					mArray.addAll(ruser.data);
					mAdapter.notifyDataSetChanged();
					mRowNum = mArray.get(mArray.size() - 1).getIntValue(
							"rownum");
					
					findViewById(R.id.right).setOnClickListener(MessageCenterActivity.this);
					((Button) findViewById(R.id.right)).setText("编辑");
				}
				else if (ruser.getState().equals("2")) 
				{showExitDialog();} 
				else {
					findViewById(R.id.tip).setVisibility(View.VISIBLE);

					findViewById(R.id.right).setOnClickListener(null);
					((Button) findViewById(R.id.right)).setText("");
				}

				((PullToRefreshListView) findViewById(R.id.listview))
						.onRefreshComplete();
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "myAppLog");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("clienttype", "android");

		MgqRestClient.post(Constants.INFOMGT, params, loginHandler);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
			finish();
			break;

		case R.id.right:
			if (findViewById(R.id.bottom).getVisibility() == View.VISIBLE)
				findViewById(R.id.bottom).setVisibility(View.GONE);
			else
				findViewById(R.id.bottom).setVisibility(View.VISIBLE);
			mAdapter.notifyDataSetChanged();
			break;

		case R.id.unread:
			delHttpRequest("1");
			break;

		case R.id.del:
			if (mSelectArray.size() == 0) {
				ToastUtil.showToastWithAlertPic("请选择操作项");
				return;
			}

			showQuery();
			break;
		}
	}

	void showQuery() {
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_query);
		mDialog.findViewById(R.id.left).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
					}
				});
		mDialog.findViewById(R.id.right).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
						delHttpRequest("9");
					}
				});
		mDialog.show();
	}
}
